import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth' // get token from cookie
import { menusTreeToMap, filterAsyncRoutes, findFirstRoutePath } from '@/utils/menus'
import { asyncRoutes } from './router'
import { setOem } from './utils/oem'
setOem()

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  console.log('router拦截to：', to)
  console.log('router拦截form：', from)

  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // step 1: 白名单
  if (whiteList.indexOf(to.path) !== -1) {
    next()
    return
  }

  // step 2: 检查token
  if (!getToken()) {
    next('/login') // 否则全部重定向到登录页
    NProgress.done()
    return
  }

  // step 3: 检查用户信息
  if (store.getters.userLoaded) {
    store.dispatch('menus/RefreshCurMenu', to) // 更新当前路由状态
    if (to.name && to.path === '/') {
      next('/404')
    } else {
      next()
    }
    return
  }

  // step 4: 用户信息
  store.dispatch('user/GetUserInfo').then(res => {
    const { spInfo } = res.data
    const menus = res.data.menus
    // 刷新用户菜单
    store.dispatch('menus/ReloadMenus', menus)
    // 挂载异步路由
    const menusMap = menusTreeToMap(menus)
    if (spInfo.type != 'SUPER' && spInfo.syncTmpServicerId) {
      // 流量预警信息
      store.dispatch('user/agentFlowAlert', {
        agentId: spInfo.syncTmpServicerId
      })
    }
    filterAsyncRoutes(asyncRoutes, menusMap)
    const firstRedirect = findFirstRoutePath(asyncRoutes)
    const firstRoute =
      {
        path: '/',
        redirect: firstRedirect,
        name: '/',
        hidden: true
      }
    const lastRoute = {
      path: '*',
      name: 'all',
      redirect: '/404',
      hidden: true
    }
    const asyncRouteList = [firstRoute, ...asyncRoutes, lastRoute]
    router.addRoutes(asyncRouteList)
    if (!to.name) {
      const curRouter = router.match(to.fullPath)
      // if (to.path === '/' && store.state.menus.homePageMenu) {
      //   next({ name: store.state.menus.homePageMenu.code })
      // } else
      if (curRouter.name && curRouter.name !== '404') {
        next({
          ...curRouter
        })
      } else {
        next('/404')
      }
      NProgress.done()
    } else {
      next()
    }
  }).catch(() => {
    store.dispatch('user/FedLogOut').then(() => {
      Message.error('登录异常，请稍后重新登录')
      next('/login')
    })
  })
})

router.afterEach(() => {
  NProgress.done()
})
